package com.xhj.myframe.myspring.annotation;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
 * -
 *
 * @author 见见 pure_xhj@163.com @Date 2021-08-22 @Time 12:13
 */
public class MyAnnotationUtil {
  public static void wright(Object obj) {
    Class<?> objClass = obj.getClass();
    Field[] declaredFields = objClass.getDeclaredFields();
    for (Field declaredField : declaredFields) {
      Name declaredAnnotation = declaredField.getDeclaredAnnotation(Name.class);
      if (declaredAnnotation != null) {
        String value = declaredAnnotation.value();
        try {
          declaredField.set(obj, value);
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
        }
      }
    }
  }

  public static void autowire(Object obj) {
    Class<?> objClass = obj.getClass();
    Field[] declaredFields = objClass.getDeclaredFields();
    for (Field declaredField : declaredFields) {
      MyAutowire declaredAnnotation = declaredField.getDeclaredAnnotation(MyAutowire.class);
      if (declaredAnnotation != null) {
        Class<?> type = declaredField.getType();
        try {
          Constructor<?> declaredConstructor = type.getDeclaredConstructor();
          Object instance = declaredConstructor.newInstance();
          wright(instance);
          declaredField.set(obj, instance);
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
        }
      }
    }
  }
}
